//
//  HomepageViewController.m
//  App-MyFairldy
//
//  Created by 客官大大 on 15/5/23.
//  Copyright (c) 2015年 客官大大. All rights reserved.
//

#import "HomepageViewController.h"

@interface HomepageViewController ()

@end

@implementation HomepageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activity.color = [UIColor blackColor];
    activity.center = self.view.center;
    [self.view addSubview:activity];
    [activity startAnimating];
    NSLog(@"%@",NSHomeDirectory());
   [self downLoadThisPageData];
    
    [activity release];
}

- (void)initTableView
{
    UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:myTableView];
    
    
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(30, 220, 320, 40);
    button1.backgroundColor = [UIColor whiteColor];
    button1.layer.borderColor = [UIColor whiteColor].CGColor;
    button1.layer.borderWidth = 1;
    button1.layer.cornerRadius = 5;
    button1.layer.masksToBounds = YES;
    [button1 setImage:[UIImage imageNamed:@"iconfont-sousuo.png"] forState:UIControlStateNormal];
    [button1 setTitle:@"请输入食物的名称" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(touchButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
    
    
    UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, self.view.frame.size.height - 430)];
    myScroll.contentSize = CGSizeMake(self.view.frame.size.width * 8, 0);
    myScroll.backgroundColor = [UIColor clearColor];
    [myScroll setContentOffset:CGPointMake(self.view.frame.size.width / 3, 0)];
    myScroll.pagingEnabled = YES;
    [self.view addSubview:myScroll];
    myScroll.showsHorizontalScrollIndicator = NO;
    myScroll.showsVerticalScrollIndicator = NO;
    
    for (int i = 0; i < self.dataArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width / 3) * i, 0, self.view.frame.size.width / 3, myScroll.frame.size.height)];
        imageView.backgroundColor = [UIColor clearColor];
        HomePageModel *model = [self.dataArray objectAtIndex:i];
        imageView.image = model.image_url;
        [myScroll addSubview:imageView];
        // 为图片添加点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchImage)];
        [imageView addGestureRecognizer:tap];
        //开启用户交互
        imageView.userInteractionEnabled = YES;
    }
    
    [myScroll release];
    [myTableView release];

}

#pragma mark UIScrollView的imageView的点击方法
- (void)touchImage
{
    HomePageSecondViewController *second = [[HomePageSecondViewController alloc] init];
    
    [self.navigationController pushViewController:second animated:YES];
}
#pragma mark Button点击跳转方法
- (void)touchButton
{
    
    HomePageFirstViewController *first = [[HomePageFirstViewController alloc] init];
    [self.navigationController pushViewController:first animated:YES];
}



- (void)downLoadThisPageData
{
    NSString *str = @"http://food.boohee.com/fb/v1/topics";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"topics"];
        self.dataArray = [NSMutableArray array];
        for (NSDictionary *dic1 in array) {
            HomePageModel *model = [HomePageModel getHomePageModel];
            model.Id = [dic1 objectForKey:@"id"];
            model.title = [dic1 objectForKey:@"title"];
            model.sub_title = [dic1 objectForKey:@"sub_title"];
            NSString *str2 = [dic1 objectForKey:@"image_url"];
            NSURL *url2 = [NSURL URLWithString:str2];
            NSData *data2 = [NSData dataWithContentsOfURL:url2];
            UIImage *image = [UIImage imageWithData:data2];
            model.image_url = image;
            [self.dataArray addObject:model];
            
            [activity stopAnimating];
            
            
            
        }
        [self initTableView];
    }];
    
}

#pragma mark tableView的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        HomePageFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[HomePageFirstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            cell.iconImage.image = [UIImage imageNamed:@"HomePagebackgroundImage.jpg"];
            return cell;
        }
        
    }else if (indexPath.row == 1){
        HomePageSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[HomePageSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            HomePageModel *model = [self.dataArray objectAtIndex:indexPath.row];
            cell.titleLabel.text = model.title;
            cell.subTitleLabel.text = model.sub_title;
            NSLog(@"%@", cell.titleLabel.text);
            return cell;
        }
        
        
    }
    return cell;
    
    

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
}
*/

@end
